import { getUserAvatarApi, getUserProfileApi, loginApi } from '@/api/user'
import { getToken, removeToken, setToken as setTokenFn } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: {}
}

const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    // 将token持久化存储到cookies中
    setTokenFn(newToken)
  },
  // 将用户信息存储到vuex中
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  // 退出，清空token、userInfo、持久化中的数据
  logOut(state) {
    state.token = ''
    state.userInfo = {}
    removeToken()
  }
}

const actions = {
  /**
   * 登录
   * @param {*} store
   * @param {*} data
   * @returns
   */
  async login(store, data) {
    const res = await loginApi(data)
    // console.log(res)
    store.commit('setToken', res.data)
    return res
  },
  // 创建获取用户信息请求方法
  async getUserInfo(store) {
    const res = await getUserProfileApi()
    // 第二份用户数据
    const res2 = await getUserAvatarApi(res.data.userId)
    // 将2份用户数据合并到一个对象中
    const result = {
      ...res.data,
      ...res2.data
    }
    store.commit('setUserInfo', result)
    console.log('vuex请求用户信息', result)
    return result
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
